from pprint import pformat

from loguru import logger
from werkzeug.exceptions import HTTPException
from flask import jsonify


class BusinessError(Exception):
    def __init__(self, message, code=400, error_type="business"):
        super().__init__(message)
        self.message = message
        self.code = code
        self.error_type = error_type


class ValidationError(BusinessError):
    def __init__(self, message, code=400):
        super().__init__(message, code, error_type="validation")


class ExcelProcessingError(BusinessError):
    def __init__(self, message, code=400):
        super().__init__(message, code, error_type="excel_processing")


class FileDownloadError(BusinessError):
    def __init__(self, message, code=400):
        super().__init__(message, code, error_type="file_download")


class AuthenticationError(BusinessError):
    def __init__(self, message, code=401):
        super().__init__(message, code, error_type="authentication")


def register_error_handlers(app):
    @app.errorhandler(HTTPException)
    def handle_http_exception(e):
        return jsonify(error=e.description, code=e.code), e.code

    @app.errorhandler(Exception)
    def handle_generic_exception(e):
        logger.info(f"response data = {pformat(e)}")
        return jsonify(error="服务器内部错误", code=500), 500

    @app.errorhandler(BusinessError)
    def handle_business_error(e):
        return jsonify(error=e.message, code=e.code, error_type=e.error_type), e.code
